import { UserState, UserStorage } from '@2/app/core/storage/user.storage';
import { Store } from 'pinia';
import { userDefineStore } from '@2/app/core/storage/define/user.define';
import { getAuthCache, setAuthCache } from '@/utils/auth';
import { SocialToken } from '@2/typings/oauth2';
import { AppUser } from '@2/typings/model/app.user';
import { PermissionModel } from '@2/typings/model/permission.model';
import { TOKEN_KEY, USER_INFO_KEY } from '@2/typings/constant/cache.c';
import { injectable } from 'inversify';
import 'reflect-metadata';
/**
 * @program: microservice-central-portal
 * @description: 用户存储接口实现
 * @author: baiHoo.chen
 * @create: 2022年5月26日
 **/
@injectable()
export class UserStorageImpl implements UserStorage {
  private readonly userStore: Store<string, UserState>;

  constructor() {
    this.userStore = userDefineStore();
  }
  /**
   * 销毁用户信息或状态信息
   */
  destroy(): void {
    this.userStore.token = undefined;
    this.userStore.LoginAppUser = null;
    this.userStore.sessionNonExpired = false;
    this.userStore.lastUpdateTime = 0;
    setAuthCache(TOKEN_KEY, undefined);
    setAuthCache(USER_INFO_KEY, null);
  }

  getLastUpdateTime(): number {
    return this.userStore.lastUpdateTime;
  }

  getToken(): SocialToken | undefined {
    return this.userStore.token || getAuthCache<SocialToken>(TOKEN_KEY);
  }

  isSessionNonExpired(): boolean {
    return this.userStore.sessionNonExpired;
  }

  setSessionNonExpired(expired: boolean): void {
    this.userStore.sessionNonExpired = expired;
  }

  setToken(token: SocialToken | undefined): void {
    this.userStore.token = token;
    setAuthCache(TOKEN_KEY, token);
  }

  getAppUser(): AppUser {
    return this.userStore.LoginAppUser || getAuthCache<AppUser>(USER_INFO_KEY) || {};
  }

  setAppUser(appUser: AppUser | null): void {
    this.userStore.LoginAppUser = appUser;
    this.userStore.lastUpdateTime = new Date().getTime();
    setAuthCache(USER_INFO_KEY, appUser);
  }
  /**
   * 返回需要使用的 定义存储对象{@see userDefineStoreWithOut}
   */
  useDefineStore(): Store<string, UserState> {
    return this.userStore;
  }

  setAppUserWithPermission(permissions: PermissionModel[]): void {
    const user: AppUser | null = this.getAppUser();
    if (user != null) {
      user.menus = permissions;
      this.setAppUser(user);
    }
  }
}
